package src.view;

import java.util.ArrayList;

import src.event.events.ConsoleUpdateEvent;
import src.event.events.MapUpdateEvent;
import src.model.gameObject.GameObjectType;
import src.model.gameWorld.GameDataObject;
import src.model.gameWorld.PlayerMap;
import src.model.gameWorld.Position;

/**
 * <b>Overview</b>
 * The MapDataCache stores information about the model that needs to be displayed to the view.  This information is cached so that several components can access the data at any time.
 *
 * <b>Responsibilities</b>
 * Maintains a graphical representation of the map to display to the user and perform updates as necessary.
 *
 * <b>Collaborators</b>
 * Viewport - Client: Viewports are instructed on what to draw based on changes to the MapDataCache.
 * EventHandler - Subcontractor: EventHandlers receive incoming events for the MapDataCache and translate them into changes to the cache.
 *
 * <b>Implementor</b> - Bruce
 * <b>Tester</b> - Tim
 *
 * @author Bruce
 */
public class MapDataCache
{
	private PlayerMap map;

	private Position [] selectedPositions;

	private GameDataObject [] selectedObjects;

	private StatusViewport sv;

	private AreaViewport av;

	public MapDataCache(StatusViewport sv, AreaViewport av)
	{
		this.sv = sv;
		this.av = av;
	}

	public void setMap(PlayerMap map)
	{
		this.map = map;
	}

	public void select(Position [] selection)
	{
		this.selectedPositions = selection;

		ArrayList<GameDataObject> list = new ArrayList<GameDataObject>();

		if(map != null)
		for(Position p : selection)
			if(map.GetObjectsAtPosition(p) != null)
			for(GameDataObject o : map.GetObjectsAtPosition(p))
			{
				String type = o.getInfo("Type");
				if(type.equals("UNIT") || type.equals("STRUCTURE"))
				{
					list.add(o);
				}
			}

		sv.updateSelection(list.toArray(new GameDataObject [0]));
	}

	public void select(int x, int y)
	{
		Position p = new Position(x, y);
		av.select(x, y);
		Position [] array = {p};
		select(array);
		if(map.GetObjectsAtPosition(p) != null)
		for(GameDataObject o : map.GetObjectsAtPosition(p))
			if(o.getType() == GameObjectType.UNIT)
				ViewEventHandler.fireEvent(new ConsoleUpdateEvent("The " + o.getInfo("Subtype").toLowerCase() + " was selected!  Neat!"));
	}

	public void forward(MapUpdateEvent e)
	{
		av.eventCallback(e);
	}
}